import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.LinkedList;


public class TCPSocketControl implements Runnable
{
	private Socket socket = null;
	private boolean runListen = false;	
	private LinkedList<Object> reciveData = new LinkedList<Object>();
	
	public Object getReciveNextData() 
	{
		return reciveData.poll();
	}
	
	public boolean hasNext()
	{
		if(reciveData.isEmpty())
		{
			return false;
		}
		else
		{
			return true;
		}
	}
	
	public TCPSocketControl() throws IOException 
	{
		this(InetAddress.getLocalHost(),11111);
	}
	
	public TCPSocketControl(Socket socket) 
	{
		this.socket = socket;
	}
	
	public TCPSocketControl(String host, int port) throws IOException 
	{
		this( InetAddress.getByName(host) ,port );
	}
	
	public TCPSocketControl(InetAddress inet, int port) throws IOException
	{
		socket = new Socket(inet, port);
	}
	
	public void sendData(Object data) throws IOException 
	{
		OutputStream os = socket.getOutputStream();
		BufferedOutputStream bis = new BufferedOutputStream(os);
		ObjectOutputStream oos = new ObjectOutputStream(bis);
		oos.writeObject(data);
	}

	public void startListen()
	{
		runListen = true;
		Thread t = new Thread(this);
		t.start();
	}

	public void stopListen()
	{
		runListen = false;
	}
	
	public void run() 
	{
		InputStream is = null;
		BufferedInputStream bis = null;
		ObjectInputStream oos = null;
		
		try 
		{
			is = socket.getInputStream();
			bis = new BufferedInputStream(is);
			oos = new ObjectInputStream(bis);
			
			synchronized (reciveData) 
			{
				while(runListen)
				{
					reciveData.offer(oos.readObject());
				}
			}
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
			runListen = false;
		} catch (ClassNotFoundException e) 
		{
			e.printStackTrace();
			runListen = false;
		}
		
		
		
		
	}
	
	
		
}

